import { bus } from "@/bus";
import { DataSource } from "typeorm";
import { createActionLog } from "./persist/actionLog";
import { OtaTask } from "@/entity/otaTask.entity";
import { Gateway } from "@/entity/gateway.entity";
import { Wristband } from "@/entity/wristband.entity";
import { ActionLogOta } from "@/entity/actionLogOta.entity";
export async function setup(AppDataSource: DataSource | null) {
    const otaTaskRepo = AppDataSource ? AppDataSource.getRepository(OtaTask) : null;
    const gatewayRepo = AppDataSource ? AppDataSource.getRepository(Gateway) : null;
    const wristbandRepo = AppDataSource ? AppDataSource.getRepository(Wristband) : null;
    const actionLogRepo = AppDataSource ? AppDataSource.getRepository(ActionLogOta) : null;
    bus.on('gw.report', async (message: any) => {
        console.log('message', message)
        // 上报升级状态
        if (message.action == 'upgrade') {
            // console.log('upgrade')
            let ota_action_log = {
                taskid: message.gw.taskId,
                gw_mac: message.gw.gw_mac,
                wb_mac: message.wb.addr.toUpperCase(),
                action: message.wb.action,
                value: message.wb.value,
                fw_name: 'bootloader',
                fw_version: message.wb.version,
                time: new Date()
            }
            // 如果 AppDataSource 存在，则存进数据库
            if (AppDataSource && otaTaskRepo && gatewayRepo && wristbandRepo && actionLogRepo) {
                // 存进数据库 actionLogOta 表
                await createActionLog(ota_action_log, otaTaskRepo, gatewayRepo, wristbandRepo, actionLogRepo);
            } else {
                console.log('AppDataSource is null, skipping database log creation');
            }
        }
    })
}